package com.frogs.ucenter.util;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.frogs.component.permission.entity.User;
import com.frogs.framework.util.file.FileUtil;
import com.frogs.framework.util.httpclient.ContentTypeEnum;
import com.frogs.framework.util.httpclient.HttpClientUtil;
import com.frogs.framework.util.httpclient.MultipartPostObject;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;

public class ImageUploadUtil {

	/**
	 * 注意：单文件上传已测试过，多文件上传未测试
	 * @author wushubin
	 * @param apiUrl
	 * @param multipartRequest
	 * @param user
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public static JSONObject uploadImage(ApiUrl apiUrl ,MultipartHttpServletRequest multipartRequest, User user) throws IllegalStateException, IOException {
    	
    	MultipartPostObject postObject = new MultipartPostObject();
    	postObject.setCharset("utf8");
    	postObject.setContentType(ContentTypeEnum.MULTIPART_FORM.getType());
    	String[] fieldName = {ApiUrlParamEnum.resourceId.getParamName() , 
    							ApiUrlParamEnum.refResource.getParamName(),
    							ApiUrlParamEnum.userId.getParamName(),
    							ApiUrlParamEnum.accountName.getParamName(),
    							apiUrl.getKeyvals()[0]};
    	
    	StringBody[] fieldValue = {new StringBody(String.valueOf(user.getUserId())) ,
					    			new StringBody("admin"),
					    			new StringBody(String.valueOf(user.getUserId())),
					    			new StringBody(user.getAccount()),
					    			new StringBody(apiUrl.getKeyvals()[1])};

    	Map<String, MultipartFile> files = multipartRequest.getFileMap();
    	String[] fileBodyName = new String[files.size()];
    	FileBody[] fileBody = new FileBody[files.size()];
    	int index = 0;
    	String realPath = FileUtil.getRealPath(multipartRequest);
    	for (Entry<String, MultipartFile> entity : files.entrySet()) {
			fileBodyName[index] = entity.getKey();
			fileBody[index] = new FileBody(transferToFile(entity, realPath));
			index++;
		}
    	
    	postObject.setFieldName(fieldName);
    	postObject.setFieldValue(fieldValue);
    	postObject.setFileBody(fileBody);
    	postObject.setFileBodyName(fileBodyName);
    	postObject.setUrl(apiUrl.getUrl());
		return (JSONObject) HttpClientUtil.multipartPost(postObject);
		
	}
	
	private static File transferToFile(Entry<String, MultipartFile> entity ,String realPath) throws IllegalStateException, IOException{
		MultipartFile multipartFile = entity.getValue();
		String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
		String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
		String filePath = FileUtil.getSaveFilePath(realPath, "/upload/images",  fileName);;
		
		File file = new File(filePath);
		multipartFile.transferTo(file);
		return file;
	}
}
